package priv.wjh.study.cloud.feign.api.config;

import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.http.HttpStatus;

import java.io.IOException;

/**
 * //TODO
 *
 * @author wangjunhao
 **/
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        String bodyStr;
        try {
            bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        } catch (IOException e) {
            return new RuntimeException(e);
        }
        HttpStatus status = HttpStatus.resolve(response.status());
        if (status == null) {
            return new RuntimeException("Http status code error!");
        }
        switch (status) {
            default: {
                return new RuntimeException(bodyStr);
            }
        }

    }
}
